//
//  EventTrackManagerΩΩ.swift
//  EventTrackSDK
//
//  Created by Army_Ma on 2020/3/2.
//  Copyright © 2020 Army_Ma. All rights reserved.
//

import UIKit

public class EventTrackManager: NSObject {

    private static let manager : EventTrackManager = EventTrackManager()
    public class func share() -> EventTrackManager {
        return manager
    }
    
    
    /*
     1. 启动  didFinishLaunchingWithOptions -> applicationDidBecomeActive   √
     2. 上滑要切后台或者退出 applicationWillResignActive  √
     3. 已经进入到后台 applicationDidEnterBackground
     4. 要进入前台运行 applicationWillEnterForeground
     5. 到了前台运行 applicationDidBecomeActive
    */
    
    public func initWithConfig(config:EventTrackConfig) {
        DataManager.appID = config.appID

        NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(willResignActive), name: UIApplication.willResignActiveNotification, object: nil)

    }
 
    @objc public func didBecomeActive() {
        print("didBecomeActive") // APP启动再前台
        self.saveCurrentTime()
    }
    
    @objc public func willResignActive() {
        print("willResignActive") // APP要退出或者切换到后台. 上滑动作会调用次方法
        self.loadLastRunTime()
//        DataManager.dataShouldUpload() //数据上传
    }
    
    func saveCurrentTime(){
        let startRunTime = Date()
        UserDefaults.standard.set(startRunTime, forKey: "startRunTime")
    }
    
    func loadLastRunTime(){//加载上次进入后台的时间
        let lastRunTime = UserDefaults.standard.object(forKey: "startRunTime")
        if lastRunTime != nil{
            let stopRunTime = lastRunTime as! Date
            let different = stopRunTime.timeIntervalSince(Date()) * -1 //计算出上次与当前时间的时间间隔
            print("上次与当前时间的时间间隔\(different)")
            let differentTime = String(format: "%.2f", different)
            
            let analyticsData = AnalyticsDataEnd()
            analyticsData.event_duration = differentTime
            
            SQLiteManager.shareManager().insertData(dataType: "AppEnd", analyticsData: analyticsData)

        }
        
    }
    
    
}
